import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class Solution {
    List<List<Integer>> result = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    boolean[] isUsed;
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        isUsed = new boolean[nums.length];
        Arrays.sort(nums);
        subsetsWithDupHelper(nums, 0);
        return result;
    }
    private void subsetsWithDupHelper(int[] nums, int startIndex){
        result.add(new ArrayList<>(path));

        for(int i = startIndex; i < nums.length; i++){
            if(i > 0 && nums[i] == nums[i-1] && !isUsed[i-1]){
                continue;
            }
            path.add(nums[i]);
            isUsed[i] = true;
            subsetsWithDupHelper(nums, i+1);
            path.remove(path.size() - 1);
            isUsed[i] = false;
        }
    }
}
